package com.sofwin.controller;

import com.sofwin.Constants;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.OperatorService;
import com.sofwin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @packageName: com.sofwin.controller
 * @user: andyliu
 * @date: 2023/5/18 15:25
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private OperatorService operatorService;
//    @PostMapping("/login")
//    public String login(SysUser user, HttpSession session){
//        SysUser loginUser = userService.login(user);
//        if(loginUser!=null){
//            // 登录成功的日志
//            session.setAttribute(Constants.CURRENT_USER,loginUser);
//            session.setMaxInactiveInterval(60*30);
//            return "redirect:index";
//        }else{
//            // 登录失败
//            return "redirect:index.jsp";
//        }
//    }
    @PostMapping("/login")
    public String login(SysUser user, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(),user.getLoginPwd());
        try{
            subject.login(token);
            SysUser loginUser = userService.login(user);
            session.setAttribute(Constants.CURRENT_USER,loginUser);
            return "redirect:index";
        }catch (Exception ex){
            return "redirect:index.jsp";
        }
    }
    @GetMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:index.jsp";
    }
}
